#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import re

from common.const import DeployType
from generaldb.gbase8a import LOGGER
from generaldb.gbase8a.common.const import RegisterType, JobType, JsonConstant


class ResourceParam:

    def __init__(self, param_dict):
        self._body_param = param_dict

    def get_param(self):
        return self._body_param

    def get_instance_or_database(self):
        register_type = self.get_val_from_extend_info(JsonConstant.FIRSTCLASSIFICATION, "0")
        try:
            is_num = int(register_type)
        except Exception:
            LOGGER.error("Failed get register type!")
            return RegisterType.ERR_TYPE
        if is_num not in [RegisterType.INSTANCE, RegisterType.DATABASE]:
            return RegisterType.ERR_TYPE
        return is_num

    def get_register_ip_list(self):
        """
        入参中获取所有ip
        """
        nodes = self._body_param.get(JsonConstant.APP_ENV, {}).get(JsonConstant.NODES, [])
        node_list = []
        for node in nodes:
            agent_ip_list = node.get(JsonConstant.EXTEND_INFO, {}).get(JsonConstant.AGENT_IP_LIST, '').split(',')
            if agent_ip_list:
                node_list.append(agent_ip_list)
        if not node_list:
            LOGGER.error("Failed get hosts!")
            return []
        return node_list

    def get_original_database_name(self):
        """
        获取修改前原本数据库名
        """
        # 数据库名称不做校验
        return self._body_param.get(JsonConstant.ORIGIN_PROTECTED_ENV, {}).get(JsonConstant.NAME)

    def get_present_database_name(self):
        """
        获取修改后数据库名
        """
        return self._body_param.get(JsonConstant.APP_ENV, {}).get(JsonConstant.NAME, "")

    def get_deploy_type(self):
        deploy_type = self.get_val_from_extend_info(JsonConstant.DEPLOY_TYPE, default_value="0")
        try:
            is_num = int(deploy_type)
        except Exception:
            LOGGER.error("Failed get deploy type!")
            return DeployType.INVALID_TYPE
        return is_num

    def get_vc_name(self):
        """
        获取vc name，无则返回空
        """
        custom_params = self.get_val_from_extend_info(JsonConstant.CUSTOM_PARAMS)
        vc_name = ""
        custom_param_arr = custom_params.split(",")
        for custom_param_ele in custom_param_arr:
            if not custom_param_ele:
                continue
            if "vc_name" in custom_param_ele:
                try:
                    vc_name = custom_param_ele.split("=")[1]
                except Exception:
                    return ""
        return vc_name

    def get_val_from_extend_info(self, key, default_value=""):
        if self._body_param.get(JsonConstant.APP_ENV):
            return self._body_param.get(JsonConstant.APP_ENV, {})\
                .get(JsonConstant.EXTEND_INFO, {}).get(key)
        elif self._body_param.get(JsonConstant.PROTECTED_ENV):
            return self._body_param.get(JsonConstant.PROTECTED_ENV, {})\
                .get(JsonConstant.EXTEND_INFO, {}).get(key)
        return default_value

    def get_register_or_change(self):
        """
        判断是注册还是修改
        """
        database_id = self._body_param.get(JsonConstant.ORIGIN_PROTECTED_ENV, {}).get(JsonConstant.ID, None)
        if not database_id:
            return JobType.REGISTER
        # 数据库名称不做校验
        return JobType.CHANGE
